#!/usr/bin/env python
# xml tree <--> sqltree converter

# $Id: main.py 3 2007-03-11 20:34:50Z fvamail $
"""
Command line interface.

"""
__all__ = [ 'main' ]

import locale
import getpass
import sys

from main_options import *
from main_utils import *

def main ( input_encoding=None , user=None , password=None ) :
    input_encoding = input_encoding or locale.getpreferredencoding(1)
    sys.argv = [ unicode(s,input_encoding).encode('utf-8') for s in sys.argv ]
    
    user = user or getpass.getuser()
    parser = create_options(user)
    (options, args) = parser.parse_args()
    process_options ( parser , options , args , user , password )

    if options.info :
        import main_info
        main_info.info ( options )
    elif options.list : list_ ( options )
    elif options.pack :
        import main_pack
        main_pack.pack ( options )
    elif options.fill : fill ( options )
    elif options.free : free ( options )
    elif options.init :
        import main_init
        main_init.init ( options )
    elif options.extract : extract ( options )
    else : insert ( options , args )
    
def list_ ( options ) :
    connect ( options )
    make_gate ( options )
    show_list ( options )
    disconnect ( options )

def show_list ( options ) :
    disconnect ( options )
    raise NotImplementedError # XXX

def fill ( options ) :
    connect ( options )
    make_gate ( options )
    options.gate.fill ( options.fill )
    disconnect ( options )

def free ( options ) :
    connect ( options )
    make_gate ( options )
    options.gate.free ( options.free )
    disconnect ( options )

def extract ( options ) :
    connect ( options )
    make_gate ( options )
    
    separate = options.output is not None and '%' in options.output 
    if options.output is None or options.output=='-' : of = sys.stdout
    elif not separate : of = file ( options.output , 'w' )

    for document in options.gate.filter( options.extract ) :
        if separate : of = file ( options.output%document , 'w' )
        options.gate.extract ( document , of , comment=options.comment ,
                               encoding=options.encoding )
        if separate : of.close()
    if not separate : of.close()
    disconnect ( options )
        
def insert ( options , args_ ) :
    connect ( options )
    make_gate ( options )

    args = args_[:]
    if not args : args = [ '-' ]        # stdin

    for name in args :
        if name == '-' :
            document = options.gate.insert ( sys.stdin )
            name = 'Standard input'
        else : document = options.gate.insert ( file(name) )
        if not options.quiet :
            print >>sys.stderr , name , ':\t' , document
    options.conn.commit()
    disconnect ( options )
#===========================================================
